<?php

/**
 * @Author:      dx
 * @DateTime:    2016-07-18 18:53:39
 * @Description: 用于维护角色的 控制器
 */
class AhpRoleController extends BaseController{

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-09 14:14:39
     * @Description: 用于展示 角色的列表的
     * @link: http://www.activity.com/ahp/ahp3.0/role/index?token=36e1c74f6aa85a2b8bf1a7796e93a0e0&page=1&page_size=1&source=1
     */
    public function index()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
                "source"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                break;
            }
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $users=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            $sr = AhpRole::with('ahp_users')->orderBy('id','desc');
            if(Input::get('id')){
                $sr->where('id',Input::get('id'));
            }
            if(Input::get('status')){
                $sr->where('status',Input::get('status'));
            }
            if(Input::get('begin_data') && Input::get('end_data')){
                $sr->whereBetween('created_at',array(Input::get('begin_data')." 00:00:00",Input::get('end_data')." 23:59:59"));
            }
            if(Input::get('source')){
                $sr->where('source',Input::get('source'));
            }
            $count = $sr->count();
            $sr=$sr->skip($page_size*($page-1))->take($page_size)->get();
            $arr_role = array();
            foreach ($sr as $_s) {
                $arr_role[]=array(
                    'id' => $_s->id,
                    "role_name"=>$_s->role_name,
                    "source"=>$_s->source,
                    "created_at"=> date('Y-m-d H:i:s',strtotime($_s->created_at)),
                    "status"=> $_s->status,
                    "created_by" => $_s->ahp_users->real_name,
                );
            }
            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"ssp_role"=>$arr_role));
        } while (false);
        Log::info("info", array("system" => "ahp" ,"event" => "role/index", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-09 14:15:39
     * @Description: 用于角色的维护
     * @link: http://www.activity.com/ahp/ahp3.0/role/store?token=36e1c74f6aa85a2b8bf1a7796e93a0e0&role_name=%E5%88%9B%E5%BB%BA%E8%A7%92%E8%89%B2&source=1
     */

    public function store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'role_name' => 'required',
                'source' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $users=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }
            $role_id = Input::get('id');
            //判断角色是否已经存在
            $exist_role = AhpRole::where('role_name',Input::get('role_name'))->where('source',Input::get('source'))->where('status','!=','3');
            if($role_id){
                $exist_role=$exist_role->where('id','!=',$role_id)->first();
            }else{
                $exist_role=$exist_role->first();
            }
            if($exist_role){
                return Response::json(array("code" => 1, "msg" =>'该角色已经存在'));
            }
            $role=AhpRole::find($role_id);
            if(!$role){//如果不存在说明是 新增
                $role=new AhpRole;
                $role->status=1;
            }
            $role->created_by = $users->id;
            $role->role_name=Input::get('role_name');
            $role->source=Input::get('source');
            $role->save();

            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "role/store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-09 14:15:39
     * @Description: 关闭角色
     * @link: http://www.activity.com/ahp/ahp3.0/role/editRoleStatus?token=36e1c74f6aa85a2b8bf1a7796e93a0e0&id=1&status=1
     */

    public function  editRoleStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'status' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ssp_sys_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ssp_sys_user)){
                break;
            }
            $id = Input::get('id');
            $status = Input::get('status');
            $ssp_role = AhpRole::find($id);
            $sys_user = AhpUsers::where('status','!=',3)->where('role_id',$id)->get()->toArray();
            if(sizeof($sys_user) > 0){
                return Response::json(array("code" => 1, "msg" =>'有用户在正常使用此角色！'));
            }
            if(!$ssp_role){
                return Response::json(array("code" => 1, "msg" => "该角色不存在"));
            } else {
                $ssp_role->status = $status;//status = 1 正常 2 冻结 3 删除̬
                $ssp_role->updated_at = date('Y-m-d H:i:s', time());
                $ssp_role->save();
            }
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "role/status", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      sqq
     * @DateTime:    2018-07-09 14:15:56
     * @Description: 修改角色获取 当前角色拥有的资源
     * @link: http://www.activity.com/ahp/ahp3.0/role/getRoleRes?token=28859210b692656c3af38e265e93635b&id=1
     */
    public function getRoleRes(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ssp_sys_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ssp_sys_user)){
                break;
            }
            $id = Input::get('id'); //角色id

            //准备 资源的显示
            $resource_arr=array();
            $resource=AhpResource::where('type',1)->whereIn('status',array(1,2))->orderBy('sort','asc')->get();//获取所有能用的资源类
            foreach ($resource as $_r) {
                $r_s=AhpResource::where('pid',$_r->id)->whereIn('status',array(1,2))->orderBy('sort','asc')->get();
                $rs_arr=array();
                foreach ($r_s as $_s) {
                    $rs_arr[]=$_s;
                }
                $_r['s_r']=$rs_arr;
                $resource_arr[]=$_r;
            }
            $role_resources = AhpRoleResource::where('role_id',$id)->select('resource_id')->get()->toArray();
            $role_res_array = array();
            foreach($role_resources as $val){
                $role_res_array[] = $val['resource_id'];
            }
            $response = array('code' => 0, 'msg' => 'ok','result' => array('role_res' => $role_res_array,'resource' => $resource_arr));
        }while(false);
        Log::info("info", array("system" => "ahp" ,"event" => "role/getRoleRes", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /**
     * @Author:      dx
     * @DateTime:    2016-07-19  14:31:17
     * @Description: 保存修改  角色的
     * @link: http://www.activity.com/ahp/ahp3.0/role/setAuth?token=28859210b692656c3af38e265e93635b&role_id=1&checkbox=[24,25,5,15,16,17,18,8,13,14,6,12,10,9]
     */
    public function setAuth(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'role_id' => 'required',
//                'resource_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("ahp_error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $ssp_sys_user=$this->verificationAhpUserToken(Input::get("token"),$response);
            if(is_null($ssp_sys_user)){
                break;
            }
            $resource_id = Input::get('checkbox');
            if(!is_array($resource_id)){
                $resource_id = json_decode($resource_id);
            }
            //获取选中的 资源的 id
            $role_id = Input::get('role_id');//获取需要修改的角色id
            AhpRoleResource::where('role_id',$role_id)->delete();//删除该角色原有的 资源
            if(!empty($resource_id)) {
                foreach ($resource_id as $val) {
                    DB::table('ahp_role_resource')->insertGetId(array(//保存 修改的 角色
                        'resource_id' => $val,
                        'role_id' => $role_id,
                        'created_at' => date('Y-m-d H:i:s', time()),
                        'updated_at' => date('Y-m-d H:i:s', time()),
                        'created_by' => $ssp_sys_user->id,
                    ));
                }
            }
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "api" ,"event" => "role/setAuth", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}